package com.frank.loadinglibrary.common;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.app.Context;

/**
 * @author SUQI
 * @date 2021/5/14
 * @description
 **/
public class DoubleCircleLoadingComponent extends BaseLoadingComponent<DoubleCircleLoadingComponent> implements Component.DrawTask {

    private Paint mPaint;
    private Color[] colors = new Color[]{Color.GRAY, Color.WHITE};
    private float[] radius = new float[]{0f, 0f};
    private AnimatorValue mAnimatorValue;

    public DoubleCircleLoadingComponent(Context context) {
        this(context, null);
    }

    public DoubleCircleLoadingComponent(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public DoubleCircleLoadingComponent(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        initPaint();
        addDrawTask(this);
        setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                startAnimators();
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {

            }
        });
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setStrokeWidth(0);
        mPaint.setStyle(Paint.Style.FILL_STYLE);
        mPaint.setAntiAlias(true);
    }

    @Override
    protected void stopAnimators() {
        if (mAnimatorValue != null) {
            mAnimatorValue.cancel();
            mAnimatorValue.end();
        }
    }

    @Override
    protected void startAnimators() {
        mAnimatorValue = new AnimatorValue();
        mAnimatorValue.setLoopedCount(Animator.INFINITE);
        mAnimatorValue.setDuration(1000);
        mAnimatorValue.setCurveType(Animator.CurveType.LINEAR);
        mAnimatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float v) {
                if (v < 0.5) {
                    radius[0] = 1 - v;
                    radius[1] = v;
                } else {
                    radius[0] = v;
                    radius[1] = 1 - v;
                }
                invalidate();
            }
        });
        mAnimatorValue.start();
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {

        float width = Math.min(getWidth(), getHeight());
        float maxRadius = width * 0.5f;
        for (int i = 0; i < 2; i++) {
            mPaint.setColor(colors[i]);
            float mRadiusValue = radius[i] * maxRadius;
            canvas.drawCircle(width * 0.5f, width * 0.5f, mRadiusValue, mPaint);
        }
    }
}
